package controller

import (
	"ez/apps/pm/auto/controller"
	pm "ez/apps/pm/document"
	"ez/apps/tool/service"
	"ez/config/code"
	"ez/custom/cc"
	"fmt"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"gitee.com/dreamwood/ez-go/tools"
	"time"
)

type FeeHouseController struct {
	controller.FeeHouseAutoController
}

func init() {
	c := &FeeHouseController{}
	c.SetRouteParam("/pm", "/admin", "FeeHouse")
	ez.CreateApi(c.AdminGet(), c.GetAction).SetRouterName("[pm]物业费_创建")
	ez.CreateApi(c.AdminList(), c.ListAction).SetRouterName("[pm]物业费_列表")
	ez.CreateApi(c.AdminSave(), c.SaveAction).SetRouterName("[pm]物业费_保存")
	ez.CreateApi(c.AdminCopy(), c.CopyAction).SetRouterName("[pm]物业费_复制")
	ez.CreateApi(c.AdminUpdate(), c.UpdateAction).SetRouterName("[pm]物业费_更新")
	ez.CreateApi(c.AdminChoice(), c.ChoiceAction).SetRouterName("[pm]物业费_选项")
	ez.CreateApi(c.AdminDelete(), c.DeleteAction).SetRouterName("[pm]物业费_删除")
	ez.CreateApi(c.AdminUnDelete(), c.UnDeleteAction).SetRouterName("[pm]物业费_恢复")
	ez.CreateApi(c.AdminDestroy(), c.DestroyAction).SetRouterName("[pm]物业费_销毁")
	ez.CreateApi(c.AdminUpdateMany(), c.UpdateManyAction).SetRouterName("[pm]物业费_更新_批量")
	ez.CreateApi(c.AdminDeleteMany(), c.DeleteManyAction).SetRouterName("[pm]物业费_删除_批量")
	ez.CreateApi(c.AdminDestroyMany(), c.DestroyManyAction).SetRouterName("[pm]物业费_销毁_批量")
	ez.CreateApi(c.AdminApi("/FeeHouse/fast_create"), c.FastCreateAction).SetRouterName("[pm]物业费_账单批量生成")
	ez.CreateApi(c.AdminApi("/FeeHouse/pay"), c.OrderPayAction).SetRouterName("[pm]物业费_确认付款")
}

// func (c FeeHouseController) AccessControl(session *ez.Session) { /* 在这里面重构 */ }
// func (c FeeHouseController) GetAction(session *ez.Session) { /* 在这里面重构 */ }
// func (c FeeHouseController) ListAction(session *ez.Session) { /* 在这里面重构 */ }
type createOrderQuery struct {
	Rows      []int64 `json:"rows"`
	PayTypeId int64   `json:"payTypeId"`
	Cut       float64 `json:"cut"`
	Note      string  `json:"note"`
}

func (c FeeHouseController) OrderPayAction(session *ez.Session) {
	query := new(createOrderQuery)
	this := cc.New(session)
	if this.Try(this.FillJson(&query)) {
		return
	}
	//检查订单是否付款过
	crud := pm.NewFeeHouseCrud()
	total := 0.0
	for _, id := range query.Rows {
		feeHouse, _ := crud.FindId(id)
		if feeHouse.Id > 0 {
			if feeHouse.IsPay {
				this.ReturnError(code.Error, "该账单已付款", 0)
				return
			}
			total += feeHouse.Amount
		} else {
			this.ReturnError(code.Error, fmt.Sprintf("账单id:%d不存在", id), 0)
			return
		}
	}
	order := new(pm.FeeHouseOrder)
	order.Cut = query.Cut
	order.Amount = total
	order.PayTypeId = query.PayTypeId
	order.Note = query.Note
	order.State = 1
	order.Sn = service.CreateSnByString(ez.ConfigService.AppId, "WYF-[YY][MM][DD]-[MAX[4]]", 1)
	order.Save()
	for _, id := range query.Rows {
		feeHouse, _ := crud.FindId(id)
		feeHouse.OrderId = order.Id
		feeHouse.IsPay = true
		feeHouse.PayTypeId = query.PayTypeId
		feeHouse.PayAt = time.Now()
		feeHouse.Save()
	}
	this.ReturnSuccess("ok", 0)

}

type fastCreateQuery struct {
	Title string    `json:"title"`
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

func (c FeeHouseController) FastCreateAction(session *ez.Session) {
	this := cc.New(session)
	query := new(fastCreateQuery)
	if this.Try(this.FillJson(&query)) {
		return
	}
	start := tools.GetMonthStart(query.Start)
	end := tools.GetMonthEnd(query.End)
	//monthCount := int(end.Sub(start).Hours() / 24 / 30)
	startYear := start.Year()
	endYear := end.Year()
	startMonth := int(start.Month())
	endMonth := int(end.AddDate(0, 0, 1).Month())
	monthCount := endYear*12 + endMonth - startYear*12 - startMonth

	done := false
	crudHouse := pm.NewHouseCrud()
	startPage := 1
	for !done {
		houseList, _ := crudHouse.FindBy(ss.M{}, []string{"id"}, startPage, 100)
		if len(houseList) == 0 {
			done = true
			break
		}
		for _, house := range houseList {
			house.LoadType()
			money := house.Type.Price * float64(monthCount) * house.Area
			feeHouse := new(pm.FeeHouse)
			feeHouse.Name = fmt.Sprintf("%s【%d%02d-%d%02d】@%s", query.Title, start.Year(), start.Month(), end.Year(), end.Month(), house.Name)
			feeHouse.StartAt = start
			feeHouse.EndAt = end
			feeHouse.HouseId = house.Id
			feeHouse.Amount = money
			_ = feeHouse.Create()
		}
		startPage++
	}

	//curdFeeHouse := pm.NewFeeHouseCrud()

	this.ReturnSuccess("OK", query)
}
